/*
 * @Author: 李无敌
 * @Date: 2025-08-01 16:03:43
 * @LastEditors: 李无敌
 * @LastEditTime: 2025-08-12 14:34:26
 * @FilePath: \nest-base\src\controllers\api-docs.controller.ts
 */
import { Controller, Get, Res } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { FastifyReply } from 'fastify';
import { SwaggerModule, DocumentBuilder, ApiExcludeController } from '@nestjs/swagger';
import { INestApplication } from '@nestjs/common';
import { SkipAuth } from '../common/decorators/roles.decorator';

@ApiExcludeController()
@Controller('api-docs')
export class ApiDocsController {
  private app: INestApplication;
  private document: any;

  constructor(private readonly configService: ConfigService) {}

  // 设置应用实例和文档
  setApp(app: INestApplication) {
    this.app = app;
    this.generateDocument();
  }

  private generateDocument() {
    if (!this.app) return;

    const swaggerConfigBuilder = new DocumentBuilder()
      .setTitle(this.configService.get('swagger.title', 'NestJS Base API'))
      .setDescription(this.configService.get('swagger.description', '企业级NestJS权限管理系统API文档'))
      .setVersion(this.configService.get('swagger.version', '1.0.0'))
      .addBearerAuth();

    const swaggerConfig = swaggerConfigBuilder.build();
    this.document = SwaggerModule.createDocument(this.app, swaggerConfig);
  }

  @Get('json')
  @SkipAuth()
  async getJsonDocs(@Res() res: FastifyReply) {
    if (!this.document) {
      this.generateDocument();
    }

    res.header('Content-Type', 'application/json');
    res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
    res.header('Pragma', 'no-cache');
    res.header('Expires', '0');
    
    return res.send(this.document);
  }

  @Get('yaml')
  async getYamlDocs(@Res() res: FastifyReply) {
    if (!this.document) {
      this.generateDocument();
    }

    // 注意：需要安装 js-yaml 依赖才能使用此功能
    // npm install js-yaml @types/js-yaml
    try {
      const yaml = require('js-yaml');
      const yamlString = yaml.dump(this.document);

      res.header('Content-Type', 'text/yaml');
      res.header('Cache-Control', 'no-cache, no-store, must-revalidate');
      res.header('Pragma', 'no-cache');
      res.header('Expires', '0');
      
      return res.send(yamlString);
    } catch (error) {
      res.header('Content-Type', 'application/json');
      return res.send({
        error: 'YAML format not available',
        message: 'Please install js-yaml dependency: npm install js-yaml @types/js-yaml',
        fallback: 'Use /api-docs/json endpoint instead'
      });
    }
  }

  @Get('info')
  async getDocsInfo(@Res() res: FastifyReply) {
    if (!this.document) {
      this.generateDocument();
    }

    const info = {
      title: this.document.info?.title || 'NestJS Base API',
      version: this.document.info?.version || '1.0.0',
      description: this.document.info?.description || '企业级NestJS权限管理系统API文档',
      paths: Object.keys(this.document.paths || {}).length,
      tags: this.document.tags?.length || 0,
      servers: this.document.servers?.length || 0,
      generatedAt: new Date().toISOString(),
      endpoints: {
        json: '/api-docs/json',
        yaml: '/api-docs/yaml',
        ui: '/api-docs',
        info: '/api-docs/info'
      }
    };

    res.header('Content-Type', 'application/json');
    return res.send(info);
  }
}
